#include "downloader.h"
#include <QListWidget>
#include <QGridLayout>
#include <QPushButton>
#include <QListWidgetItem>
#include <QSpacerItem>
#include <QMessageBox>
#include <QUrl>
#include <QFile>
#include <QHash>
#include "httpget.h"
#include "settings.h"

Downloader *downloader = NULL;

Downloader::Downloader(QWidget *parent) :
    QWidget(parent)
{
    n_downloading = 0;
    listWidget = new QListWidget;
    QPushButton *playButton = new QPushButton(tr("Play"));
    QPushButton *delButton = new QPushButton(tr("Delete"));
    QPushButton *pauseButton = new QPushButton(tr("Pause"));
    QSpacerItem *spacer = new QSpacerItem(40, 20, QSizePolicy::Expanding);

    QGridLayout *layout = new QGridLayout(this);
    layout->addItem(spacer, 0, 0, 1, 1);
    layout->addWidget(playButton, 0, 1, 1, 1);
    layout->addWidget(delButton, 0, 2, 1, 1);
    layout->addWidget(pauseButton, 0, 3, 1, 1);
    layout->addWidget(listWidget, 1, 0, 1, 4);

    setWindowTitle(tr("Download Manager"));

    connect(playButton, SIGNAL(clicked()), this, SLOT(onPlayButton()));
    connect(delButton, SIGNAL(clicked()), this, SLOT(onDelButton()));
    connect(pauseButton, SIGNAL(clicked()), this, SLOT(onPauseButton()));

    downloader = this;
}


void Downloader::addTask(const QString &url, const QString &filename)
{
    //rename if the same file is exist
    QString name = filename;
    int i = 0;
    while (QFile::exists(name))
    {
        i++;
        name = '[' + QString::number(i) + ']' + filename;
    }

    //Start downloading
    HttpGet *get = new HttpGet(url, name, this);
    connect(get, SIGNAL(finished(HttpGet*,bool)), this, SLOT(onFinished(HttpGet*,bool)));
    connect(get, SIGNAL(paused(HttpGet*)), this, SLOT(onPaused(HttpGet*)));
    connect(get, SIGNAL(progressChanged(HttpGet*,int)), this, SLOT(onProgressChanged(HttpGet*,int)));
    if (n_downloading < Settings::maxTasks) {
        get->start();
        n_downloading++;
    }
    else
        waitings << get;

    //Create item
    QListWidgetItem *item = new QListWidgetItem("[wait] " + name);
    get2item[get] = item;
    item2get[item] = get;
    listWidget->addItem(item);
}

void Downloader::onFinished(HttpGet *get, bool error)
{
    QListWidgetItem *item = get2item[get];
    QString name = get->getFileName();
    if (error)
        item->setText("[Error] " + name);
    else
        item->setText("[Done]  " + name);
    get2item.remove(get);
    item2get[item] = NULL;
    n_downloading--;
    if (n_downloading < Settings::maxTasks && !waitings.isEmpty())
    {
        waitings.takeFirst()->start();
        n_downloading++;
    }
}

void Downloader::onPlayButton()
{
    QListWidgetItem *item = listWidget->currentItem();
    if (!item)
        return;

    QString name = item->text();
    if (!name.startsWith("[Done]  ")) //haven't finished
    {
        QMessageBox::warning(this, "warning", tr("File is downloading."));
        return;
    }

    name = name.mid(8);
    emit newPlay(name.section('/', -1), name);
}

void Downloader::onDelButton()
{
    QListWidgetItem *item = listWidget->currentItem();
    if (!item)
        return;

    QString name = item->text();
    if (!name.startsWith("[Done]  ") && !name.startsWith("[Error] "))
    {
        QMessageBox::warning(this, "warning", tr("File is downloading."));
        return;
    }
    item2get.remove(item);
    delete item;
}

void Downloader::onPauseButton()
{
    QListWidgetItem *item = listWidget->currentItem();
    if (!item)
        return;
    HttpGet *get = item2get[item];
    if (get == NULL || item->text().startsWith("[wait] "))
        return;
    get->pause();
}

void Downloader::onProgressChanged(HttpGet *get, int percent)
{
    QListWidgetItem *item = get2item[get];
    item->setText('[' + QString::number(percent) + "%]  " + get->getFileName());
}

void Downloader::onPaused(HttpGet *get)
{
    QListWidgetItem *item = get2item[get];
    item->setText("[pause] " + get->getFileName());
}
